# 战斗场景主脚本 - 连接所有战斗系统组件
extends Node2D

# 导入必要的类
const _Character = preload("res://scripts/character.gd")
const _Player = preload("res://scripts/player.gd")
const _Enemy = preload("res://scripts/enemy.gd")
const _BattleManager = preload("res://scripts/battle_manager.gd")
# 移除对BattleUI的预加载，避免在脚本加载阶段遇到问题

# 战斗管理器实例
var battle_manager: BattleManager

# 战斗角色
var player_characters: Array = []
var enemy_characters: Array = []

# UI引用
var battle_ui: Control

# 当前选中的目标
var selected_target: Character = null

# 指令安排跟踪
var commands_assigned: Dictionary = {}
var commands_needed: int = 0


func _ready():
	# 初始化战斗管理器
	battle_manager = BattleManager.new(self)

	# 初始化玩家和敌人角色
	_initialize_characters()

	# 获取BattleUI节点
	var battle_ui_node = null
	if has_node("BattleUI"):
		battle_ui_node = $BattleUI
	else:
		print("警告: 找不到BattleUI节点，UI功能将不可用")

	# 让战斗管理器知道UI节点
	battle_manager.set_battle_ui(battle_ui_node)
	print("enemy_characters", enemy_characters.size(),player_characters.size())
	# 开始战斗
	battle_manager.start_battle(player_characters, enemy_characters)

	# 初始化指令跟踪系统
	init_command_tracking()


# 初始化角色
func _initialize_characters():
	# 初始化玩家角色
	# 第一个玩家角色 - 英雄
	var player1_node = $PlayerTeamContainer/Player1
	var player1_sprite = player1_node.get_node("Player1Sprite") if player1_node.has_node("Player1Sprite") else null

	var player1 = _Player.new(player1_node, player1_sprite, "Hero")
	player1.max_hp = 150
	player1.current_hp = 150
	player1.attack = 15
	player1.defense = 8
	player1.speed = 6
	player1.skills = [
		{"type": "attack", "power": 20, "mp_cost": 10}, {"type": "heal", "power": 30, "mp_cost": 15}
	]
	player1.items = [{"type": "potion", "power": 50, "name": "治疗药水"}]
	player_characters.append(player1)

	# 第二个玩家角色 - 法师
	var player2_node = null
	var player2_sprite = null
	# 尝试获取现有节点，如果不存在则创建临时节点（实际游戏中应该在场景编辑器中预先创建）
	if has_node("PlayerTeamContainer/Player2"):
		player2_node = $PlayerTeamContainer/Player2
		player2_sprite = player2_node.get_node("Player2Sprite") if player2_node.has_node("Player2Sprite") else null
	else:
		# 创建临时节点
		player2_node = Node2D.new()
		player2_node.name = "Player2"
		player2_node.position = Vector2(150, 300) # 放置在第一个玩家旁边
		$PlayerTeamContainer.add_child(player2_node)

	var player2 = _Player.new(player2_node, player2_sprite, "Mage")
	player2.max_hp = 100
	player2.current_hp = 100
	player2.attack = 8
	player2.defense = 5
	player2.speed = 8
	player2.skills = [
		{"type": "fireball", "power": 25, "mp_cost": 20}, {"type": "lightning", "power": 30, "mp_cost": 25}
	]
	player2.items = [{"type": "mana_potion", "power": 30, "name": "魔法药水"}]
	player_characters.append(player2)

	# 初始化敌人角色
	# 第一个敌人 - 史莱姆
	var enemy1_node = $EnemyTeamContainer/Enemy1
	var enemy1_sprite = enemy1_node.get_node("Enemy1Sprite") if enemy1_node.has_node("Enemy1Sprite") else null

	var enemy1 = _Enemy.new(enemy1_node, enemy1_sprite, "Slime")
	enemy1.max_hp = 80
	enemy1.current_hp = 80
	enemy1.attack = 10
	enemy1.defense = 3
	enemy1.speed = 4
	enemy1.enemy_type = "Normal"
	enemy1.exp_reward = 15
	enemy1.gold_reward = 8
	enemy1.ai_strategy = "normal"
	enemy_characters.append(enemy1)

	# 第二个敌人 - 骷髅
	var enemy2_node = null
	var enemy2_sprite = null
	# 尝试获取现有节点，如果不存在则创建临时节点
	if has_node("EnemyTeamContainer/Enemy2"):
		enemy2_node = $EnemyTeamContainer/Enemy2
		enemy2_sprite = enemy2_node.get_node("Enemy2Sprite") if enemy2_node.has_node("Enemy2Sprite") else null
	else:
		# 创建临时节点
		enemy2_node = Node2D.new()
		enemy2_node.name = "Enemy2"
		enemy2_node.position = Vector2(500, 300) # 放置在第一个敌人旁边
		$EnemyTeamContainer.add_child(enemy2_node)

	var enemy2 = _Enemy.new(enemy2_node, enemy2_sprite, "Skeleton")
	enemy2.max_hp = 100
	enemy2.current_hp = 100
	enemy2.attack = 12
	enemy2.defense = 5
	enemy2.speed = 6
	enemy2.enemy_type = "Normal"
	enemy2.exp_reward = 20
	enemy2.gold_reward = 10
	enemy2.ai_strategy = "normal"
	enemy_characters.append(enemy2)


# 战斗管理器将直接处理UI事件，这些函数已在battle_ui.gd中实现


# 选择目标
func select_target(target: Character):
	selected_target = target
	# 这里可以添加视觉反馈，如高亮显示选中的目标


# 更新UI显示
func update_ui():
	# 更新角色状态显示（可以添加HP条、MP条等）
	# 这里简化处理，实际应该有更复杂的UI更新逻辑
	pass


# 初始化指令跟踪系统
func init_command_tracking():
	commands_assigned.clear()
	commands_needed = 0

	# 计算需要安排指令的玩家角色数量
	for player in player_characters:
		if player.is_alive:
			commands_needed += 1
			commands_assigned[player.name] = false

	# 初始化完成后启用指令UI
	if battle_manager:
		battle_manager.enable_command_ui()


# 处理玩家角色指令安排
func assign_command_to_player(player_name: String, _action_type: String, _target: Character = null):
	# 记录该角色已分配指令
	commands_assigned[player_name] = true

	# 检查是否所有玩家角色都已分配指令
	if check_all_commands_assigned():
		# 所有指令安排完成，开始战斗执行阶段
		battle_manager.start_battle_execution()

	# 注意：在实际系统中，这里应该将指令存储起来，
	# 然后在战斗执行阶段按照回合顺序执行这些指令


# 检查是否所有玩家角色都已分配指令
func check_all_commands_assigned():
	var assigned_count = 0
	for key in commands_assigned:
		if commands_assigned[key]:
			assigned_count += 1

	return assigned_count >= commands_needed


# 处理战斗结束
func on_battle_end(is_victory: bool):
	# 战斗结束后的处理逻辑
	if is_victory:
		print("战斗胜利！")
	else:
		print("战斗失败！")

	# 可以添加返回主菜单或进入下一关的逻辑


# 处理回合结束，重新初始化指令跟踪
func on_turn_end():
	# 在新回合开始前重新初始化指令跟踪
	init_command_tracking()
